﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Web;

namespace Sunny.Lib
{
    public class HttpHelper
    {
        public static Dictionary<string, string> ParseRequestString2Parameters(string request, bool isNeedDecode = true, char[] delimiters = null)
        {
            if (delimiters == null)
            {
                delimiters = new char[] { '&' };
            }
            Dictionary<string, string> requestInfo = new Dictionary<string, string>();

            string[] parts = request.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
            foreach (string part in parts)
            {
                int index = part.IndexOf('=');
                if (index > 1)
                {
                    string key = part.Substring(0, index).Trim();
                    string value = part.Substring(index + 1).Trim();
                    if (isNeedDecode)
                    {
                        value = HttpUtility.UrlDecode(value);
                    }

                    requestInfo.Add(key, (value));
                }
            }

            return requestInfo;
        }

        public static string ConcatenatedParameters2RequestString(Dictionary<string, string> AllRequestParams)
        {
            StringBuilder builder = new StringBuilder();
            foreach (KeyValuePair<string, string> temp in AllRequestParams)
            {
                builder.Append(temp.Key + "=" + HttpUtility.UrlEncode(temp.Value) + "&");
                //builder.Append(temp.Key + "=" + temp.Value + "&");
            }

            //Remove the last &
            int nLen = builder.Length;
            builder.Remove(nLen - 1, 1);

            return builder.ToString();
        }

        //private static string UrlEncode(string requestParameters)
        //{
        //    StringBuilder sb = new StringBuilder();
        //    Dictionary<string, string> parameters = HttpHelper.ParseRequestParameters(requestParameters);
        //    foreach (var p in parameters)
        //    {
        //        sb.Append(string.Format("{0}={1}&", p.Key, HttpUtility.UrlEncode(p.Value)));
        //    }

        //    return sb.ToString().Trim('&');
        //}
    }
}

